import { Toast } from 'antd-mobile';
import {
  dislikeCommentByIdAPI,
  likeCommentByIdAPI,
  sendCommentByIdAPI,
  SendCommentParms,
} from '@/api/comment';
import { getCommentsByIdAPI } from '@/api/comment';
import store, { AppDispatch } from '..';
import { ActionType, CommentItemType } from '../reducer/comment';

export const getCommentsByIdAction = (id: string, type: 'a' | 'c', last_id?: string) => {
  return async (disaptch: AppDispatch) => {
    const res = await getCommentsByIdAPI(id, type, last_id);
    disaptch({ type: 'comment/saveComment', payload: res.data });
  };
};

export const clearCommentAction = (): ActionType => ({
  type: 'comment/clearComent',
});

export const saveOriginAction = (payload: CommentItemType): ActionType => ({
  type: 'comment/saveOrigin',
  payload,
});

export const sendCommentAction = (data: SendCommentParms) => {
  return async (disaptch: AppDispatch) => {
    const res = await sendCommentByIdAPI(data);
    disaptch({ type: 'comment/updateComment', payload: res.data.new_obj });
  };
};
// 3. 定义回复评论的action
/** 对评论进行回复 */
export const sendToComnentAction = (data: SendCommentParms) => {
  return async (disaptch: AppDispatch) => {
    await sendCommentByIdAPI(data);
  };
};

export const likeCommentAction = (id: string) => {
  return async (disaptch: AppDispatch, getState: typeof store.getState) => {
    const commentList = getState().comment.commentData.results;
    const commentItem = commentList.find((item) => item.com_id === id);
    const isLiking = commentItem?.is_liking;
    if (isLiking) {
      await dislikeCommentByIdAPI(id);
    } else {
      await likeCommentByIdAPI(id);
    }
    disaptch({ type: 'comment/likeComment', payload: id });
    Toast.show({ content: isLiking ? '取消成功' : '点赞成功' });
  };
};

export const getReplyByIdAction = (id: string) => {
  return async (dispatch: AppDispatch) => {
    const res = await getCommentsByIdAPI(id, 'c');
    dispatch({ type: 'comment/saveReply', payload: res.data });
  };
};
